from django.shortcuts import render
from decimal import Decimal
import json
from django import http
from django.utils import timezone

from meiduo_mall.utils.views import LoginRequiredView
from users.models import Address
from django_redis import get_redis_connection
from goods.models import SKU
from .models import OrderInfo, OrderGoods
from meiduo_mall.utils.response_code import RETCODE


class OrderSettlementView(LoginRequiredView):
    """结算订单"""

    def get(self, request):
        """提供订单结算页面"""
        # 获取登录用户
        user = request.user
        # 查询地址信息

        addresses = Address.objects.filter(user=request.user, is_deleted=False)

        # 如果地址为空，渲染模板时会判断，并跳转到地址编辑页面
        addresses = addresses or None

        # 从Redis购物车中查询出被勾选的商品信息
        redis_conn = get_redis_connection('carts')
        redis_cart = redis_conn.hgetall('carts_%s' % user.id)
        cart_selected = redis_conn.smembers('selected_%s' % user.id)
        cart = {}
        for sku_id in cart_selected:
            cart[int(sku_id)] = int(redis_cart[sku_id])

        # 准备初始值
        total_count = 0
        total_amount = Decimal('0.00')
        # 查询商品信息
        skus = SKU.objects.filter(id__in=cart.keys())
        for sku in skus:
            sku.count = cart[sku.id]
            sku.amount = sku.count * sku.price
            # 计算总数量和总金额
            total_count += sku.count
            total_amount += sku.count * sku.price
        # 补充运费
        freight = Decimal('10.00')

        # 渲染界面
        context = {
            'addresses': addresses,
            'skus': skus,
            'total_count': total_count,
            'total_amount': total_amount,
            'freight': freight,
            'payment_amount': total_amount + freight
        }

        return render(request, 'place_order.html', context)


class OrderCommitView(LoginRequiredView):
    """提交订单"""

    def post(self, request):

        # 1. 接收
        json_dict = json.loads(request.body.decode())
        address_id = json_dict.get('address_id')
        pay_method = json_dict.get('pay_method')
        user = request.user
        # 2. 校验
        try:
            address = Address.objects.get(id=address_id, user=user, is_deleted=False)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('收货地址有误')
        if pay_method not in [OrderInfo.PAY_METHODS_ENUM['CASH'], OrderInfo.PAY_METHODS_ENUM['ALIPAY']]:
            return http.HttpResponseForbidden('支付方式有误')

        # 根据用户选择的支付方式来判断订单初始状态
        status = (OrderInfo.ORDER_STATUS_ENUM['UNPAID']
                  if pay_method == OrderInfo.PAY_METHODS_ENUM['ALIPAY']
                  else OrderInfo.ORDER_STATUS_ENUM['UNSEND'])

        # 订单编号: 20191201100728 + 00000001
        order_id = timezone.now().strftime('%Y%m%d%H%M%S') + '%09d' % user.id
        # 3. 新增订单基本信息记录 OrderInfo
        order_model = OrderInfo.objects.create(
            order_id=order_id,
            user=user,
            address=address,
            total_count=0,
            total_amount=Decimal('0.00'),
            freight=Decimal('10.00'),
            pay_method=pay_method,
            status=status
        )

        # 创建redis连接
        redis_conn = get_redis_connection('carts')
        # 将hash set中所有数据获取出来
        redis_carts = redis_conn.hgetall('carts_%s' % user.id)
        selected_ids = redis_conn.smembers('selected_%s' % user.id)
        # 将redis购物车数据过滤,只留下要购买商品id和count
        sku_dict = {}  # 包装要购买商品sku_id : count
        for sku_id_bytes in selected_ids:
            sku_dict[int(sku_id_bytes)] = int(redis_carts[sku_id_bytes])
        # 遍历要购买商品的字典,进行对每个商品逐个下单
        for sku_id in sku_dict:
            # 查询sku模型
            sku = SKU.objects.get(id=sku_id)
            # 购买量
            buy_count = sku_dict[sku_id]
            # 原始库存
            origin_stock = sku.stock
            # 原始销量
            origin_sales = sku.sales
            # 判断库存,如果库存不足就下单失败
            if buy_count > origin_stock:
                return http.JsonResponse({'code': RETCODE.STOCKERR, 'errmsg': '库存不足'})

            # 修改sku 的库存和销量
            # 新库存
            new_stock = origin_stock - buy_count
            # 新销量
            new_sales = origin_sales + buy_count
            sku.stock = new_stock
            sku.sales = new_sales
            sku.save()

            # 修改spu 销量
            spu = sku.spu
            spu.sales += buy_count
            spu.save()

            # 新增订单商品记录  OrderGoods
            OrderGoods.objects.create(
                order_id=order_id,
                sku=sku,
                count=buy_count,
                price=sku.price
            )

            # 修改订单中购买商品总数量
            order_model.total_count += buy_count
            # 修改订单中总金额
            order_model.total_amount += (sku.price * buy_count)

        # 最最后单独累加一次运费
        order_model.total_amount += order_model.freight
        order_model.save()

        # 删除购物车中已被购买的商品
        # pl = redis_conn.pipeline()
        # pl.delete('selected_%s' % user.id)
        # pl.hdel('carts_%s' % user.id, *selected_ids)
        # pl.execute()
        # 响应 json 订单编号
        pass
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'order_id': order_id})

